package ca.cbc.medialib.service;

import ca.cbc.medialib.Bootstrap;

import com.google.gson.Gson;
import com.theplatform.data.api.exception.ObjectNotFoundException;
import com.theplatform.data.notification.api.client.NotificationClient;
import com.theplatform.data.notification.api.client.NotificationCommitter;
import com.theplatform.data.notification.api.client.NotificationListener;
import com.theplatform.data.notification.api.objects.Notification;
import com.theplatform.module.exception.AuthenticationException;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This is a simple implementation of a notification listener that writes all notifications
 * out to System.out.
 */
public class SystemOutNotificationListener implements NotificationListener
{
	private NotificationClient notificationClient;
	
	public void setNotificationClient(NotificationClient notificationClient) {
		this.notificationClient = notificationClient;
	}
	
	private static Logger logger = LoggerFactory.getLogger(SystemOutNotificationListener.class);
	public void receiveNotifications(List<Notification> notifications, NotificationCommitter committer)
	{
		// print the basic info from the notification
		for (Notification notification : notifications)
		{
			logger.info(notification.getId() + " " + notification.getObjectType()
				+ " " + notification.getMethod() + " " + notification.getEntry() + " " + new Gson().toJson(notification.getEntry()));
		}

		// tell the notification client that we've processed the current notification
		committer.commit();
	}

	public void onException(Throwable e) {
		try {
			throw e;
		} catch(ObjectNotFoundException ex) {	
			logger.info("Can not find sequence, will use olese avaible notification (7 days from now).", ex);
			notificationClient.setSequence(-1L);
		} catch(AuthenticationException ex) {
			logger.info("Authentication Exception, will reset token.", ex);
			notificationClient.stop();
			notificationClient.setAuthorization(Bootstrap.instance.getAuthenticationClient());
		} catch (Throwable ex) {
			logger.error("Unknow Exception!", e);
		}
	}
}
